﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;
using System.Printing;
using MyHelper;
using HandyControl.Controls;
using System.Threading;
using System.Windows.Interop;
using System.Net.NetworkInformation;
using System.Windows.Markup;
using System.Security.Policy;
using clf.weighing.entity;
using Brushes = System.Windows.Media.Brushes;
using Image = System.Windows.Controls.Image;
using Timer = System.Threading.Timer;
using PrintDialog = System.Windows.Controls.PrintDialog;
using UserControl = System.Windows.Controls.UserControl;

namespace weighing
{
    /// <summary>
    /// PrintWindow.xaml 打印 的交互逻辑
    /// </summary>
    public partial class PrintWindow : GlowWindow
    {
        #region variables
        private WeighingBillVo? mWeighingBillVo = null;
        private WeighingBill? mWeighingBill = null;
        private Int64 mBillId;
        private bool isAutoPrint;
        /// <summary>
        /// after 3s close this window 
        /// </summary>
        private Timer mTime;
        private bool isClickPrint = false;
        private bool isCaptured = false;

        private System.Timers.Timer CuontDownPrintTimer;

        /// <summary>
        /// 打印内容的类型
        /// </summary>
        private WeightingBillType mPrintType;
        #endregion

        /// <summary>
        /// 打印窗口
        /// </summary>
        /// <param name="billId">过磅单ID</param>
        /// <param name="printType">打印内容的类型</param>
        public PrintWindow(Int64 billId, WeightingBillType printType)
        {
            InitializeComponent();

            CommonFunction.ShowCustomIcon(this);
            mBillId = billId;
            mPrintType = printType;

            if (printType == WeightingBillType.WeighintBill)
            {
                isAutoPrint = App.Config.BillPrintConfig.AutoPrint;
            }           
        }
        #region window event
        private void Print_Window_Loaded(object sender, RoutedEventArgs e)
        {
            string msg = "没有要打印的磅单 ，窗口将闭关。";
            if (mBillId <= 0)
            {
                CommonFunction.AlertInfo(msg, this);
                this.Close();
                return;
            }
            else
            {
                mWeighingBill = WeighingBillDao.Instance.FindById(mBillId);         
                if (mWeighingBill == null)
                {                  
                    CommonFunction.AlertInfo(msg, this);
                    this.Close();
                }
                else
                {
                    mWeighingBillVo = new WeighingBillVo(mWeighingBill);
                    if (mWeighingBill.type == (int)WeightingBillType.Buy)
                    {
                        isAutoPrint = App.Config.BillPrintConfig.AutoPrintLoadBill;
                    }
                    else if (mWeighingBill.type == (int)WeightingBillType.Sale)
                    {
                        isAutoPrint = App.Config.BillPrintConfig.AutoPrintUnloadBill;
                    }
                    else
                    {
                        isAutoPrint = false;
                    }
                }
            }
        }

        private void Print_Window_ContentRendered(object sender, EventArgs e)
        {
            if (mPrintType == WeightingBillType.WeighintBill)
            {
                //不完成，不能打印
                if (mWeighingBillVo.Status == (int)BillStatus.Finished)
                {
                    this.WeighingBillRb.IsEnabled = true;
                    this.WeighingBillRb.IsChecked = true;
                }
                else
                {
                    this.WeighingBillRb.IsEnabled = false;
                    this.WeighingBillRb.IsChecked = false;
                }
            }
            else if (mPrintType == WeightingBillType.ExitSlip)
            {
                //不完成，不能打印
                if (mWeighingBillVo.Status == (int)BillStatus.Finished)
                {
                    this.ExitSlipRb.IsEnabled = true;
                    this.ExitSlipRb.IsChecked = true;
                }
                else
                {
                    this.ExitSlipRb.IsEnabled = false;
                    this.ExitSlipRb.IsChecked = false;
                }
            }
            else if (mPrintType == WeightingBillType.LoadingBill)
            {
                //不是销售，不能打印
                if (mWeighingBillVo.Type == (int)WeightingBillType.Sale)
                {
                    this.loadingBillRb.IsEnabled = true;
                    this.loadingBillRb.IsChecked = true;
                }
                else
                {
                    this.loadingBillRb.IsEnabled = false;
                    this.loadingBillRb.IsChecked = false;
                }
            }
            else if (mPrintType == WeightingBillType.UnLoadingBill)
            {
                //不是采购，不能打印
                if (mWeighingBillVo.Type == (int)WeightingBillType.Buy)
                {
                    this.UnloadingBillRb.IsEnabled = true;
                    this.UnloadingBillRb.IsChecked = true;
                }
                else
                {
                    this.UnloadingBillRb.IsEnabled = false;
                    this.UnloadingBillRb.IsChecked = false;
                }
            }
            else
            {
                CommonFunction.AlertInfo("打印类型未知", this);
            }

            if (mWeighingBillVo.Type == (int)WeightingBillType.Buy)
            {
                this.loadingBillRb.IsEnabled = false;
                this.loadingBillRb.Visibility = Visibility.Collapsed;
            }
            else if (mWeighingBillVo.Type == (int)WeightingBillType.Sale)
            {
                this.UnloadingBillRb.IsEnabled = false;
                this.UnloadingBillRb.Visibility = Visibility.Collapsed;
            }
            if (mWeighingBillVo.Status == (int)BillStatus.NoOut)
            {
                this.WeighingBillRb.IsEnabled = false;
                this.WeighingBillRb.Visibility = Visibility.Visible;

                this.ExitSlipRb.IsEnabled = false;
                this.ExitSlipRb.Visibility = Visibility.Collapsed;
            }
        }

        private void Print_Window_Closing(object sender, System.ComponentModel.CancelEventArgs e)
        {
            mTime?.Dispose();
            CuontDownPrintTimer?.Dispose();
            if (!isCaptured)
            {
                UICapture();
            }
        }

        private void Print_Window_KeyUp(object sender, System.Windows.Input.KeyEventArgs e)
        {
            if (e.Key == Key.Escape)
            {
                this.Close();
            }
        }
        #endregion
        /// <summary>
        /// check print times
        /// </summary>
        /// <returns></returns>
        private bool VerifyPrintTimes()
        {
            if (mWeighingBill?.type == (int)WeightingBillType.ExitSlip)
            {
                //unlimited exit slip print times
                return true;
            }
            if (mWeighingBill?.type == (int)WeightingBillType.Buy)
            {
                return (mWeighingBill?.printTimes ?? 0) < App.Config.BillPrintConfig.LimitInPrintTimes;
            }
            else if (mWeighingBill?.type == (int)WeightingBillType.Sale)
            {
                return (mWeighingBill?.printTimes ?? 0) < App.Config.BillPrintConfig.LimitOutPrintTimes;
            }
            else
            {
                //other type unlimited print times
                return true;
            }

        }
        private SysCustomizeBillVo? GetCustomerBillVo(WeightingBillType type)
        {
            var v = SysCustomizeBillDao.Instance.FindUserdByType(type);
            if (v == null) return null;
            return new SysCustomizeBillVo(v);
        }


        private void SetCustromerUi(SysCustomizeBillVo vo)
        {
            if (vo != null)
            {
                var content = vo.Content;
                if (string.IsNullOrEmpty(content))
                {
                    CommonFunction.AlertInfo("没有在磅单里设计任何打印内容");
                    return;
                }
                Canvas canvas = new Canvas()
                {
                    Width = (vo.PrintWidth ?? 700) + (vo.LeftDistance ?? 0),
                    Height = (vo.PrintHeight ?? 350) + (vo.TopDistance ?? 0),
                    Name = "mainCanvas",
                    Background = Brushes.White,
                    //Margin = new Thickness(10, 0, 10, 0),
                };
                List<string> nodes = (List<string>)JsonHelper.JsonToObject(content, typeof(List<string>));
                if (nodes == null || nodes.Count <= 0)
                {
                    var msg = "没有在磅单里设计任何打印项，请完成自定义磅单。";
                    CommonFunction.AlertInfo(msg);
                    return;
                }

                // start build 
                for (int i = 0; i < nodes.Count; i++)
                {
                    string itemXaml = nodes[i];
                    string decodeXaml = UrlHelper.Decode(itemXaml);
                    foreach (var assembely in Constant.relpaceAssemblys)
                    {
                        decodeXaml = decodeXaml.Replace(assembely, Constant.currAssembly);
                    }
                    var ui = XamlReader.Parse(decodeXaml);

                    if (ui is DragUc uc)
                    {
                        uc.isCanDrag = false;
                        //if (!uc.Name.StartsWith(Constract.StaticTextNamePre))
                        //{
                        //    var v = GetBillValue(uc.Name.Replace("Uc", ""));
                        //    //uc.SetValueText(v);
                        //    uc.TextValue = v;
                        //}
                        var nuc = new DragUc() { };
                        nuc.isCanDrag = false;
                        Border border = uc.Content as Border;
                        Border newborder = new Border()
                        {
                            BorderBrush = border.BorderBrush,
                            BorderThickness = border.BorderThickness
                        };
                        var oldWrapPanel = border.Child as WrapPanel;

                        WrapPanel wp = new WrapPanel()
                        {
                            HorizontalAlignment = oldWrapPanel.HorizontalAlignment,
                            VerticalAlignment = oldWrapPanel.VerticalAlignment,
                        };

                        TextBlock otb1 = oldWrapPanel.Children[0] as TextBlock;

                        var tb1 = new TextBlock()
                        {
                            Text = otb1.Text,
                            Visibility = otb1.Visibility,
                            FontSize = otb1.FontSize,
                            Width = otb1.Width,
                            Height = otb1.Height,
                        };
                        wp.Children.Add(tb1);
                        TextBlock otb2 = oldWrapPanel.Children[1] as TextBlock;
                        var tb2 = new TextBlock()
                        {
                            Text = otb2.Text,
                            Visibility = otb2.Visibility,
                            FontSize = otb2.FontSize,
                            Width = otb1.Width,
                            Height = otb1.Height,
                        };
                        wp.Children.Add(tb2);
                        TextBlock otb3 = oldWrapPanel.Children[2] as TextBlock;
                        var tb3 = new TextBlock()
                        {
                            Text = otb3.Text,
                            Visibility = otb3.Visibility,
                            FontSize = otb3.FontSize,
                            Width = otb1.Width,
                            Height = otb1.Height,
                            Margin = new Thickness(2, 0, 2, 0),
                        };
                        if (!uc.Name.StartsWith(Constant.StaticTextNamePre))
                        {
                            if (uc.Name.StartsWith("printDateTime") || uc.Name.StartsWith("PrintDateTime"))
                            {
                                // tb3.Text = CommonFunction.GetPrintTimeStr(mWeighingBillVo);
                                tb3.Text = DateTimeHelper.getCurrentDateTime();
                            }
                            else
                            {
                                var v = GetBillValue(uc.Name.Replace("Uc", ""));
                                tb3.Text = v;
                            }
                        }
                        wp.Children.Add(tb3);

                        newborder.Child = wp;
                        nuc.Content = newborder;
                        Canvas.SetLeft(nuc, Canvas.GetLeft(uc));
                        Canvas.SetTop(nuc, Canvas.GetTop(uc));
                        canvas.Children.Add(nuc);
                    }
                    else if (ui is DragLineUc lineUc)
                    {
                        if (lineUc.Name.Equals(Constant.QrCodeName) || lineUc.Name.Equals(Constant.BarCodeName))
                        {
                            Border border = lineUc.Content as Border;
                            Image img = border.Child as Image;                           
                        }
                        //lineUc.MouseLeftButtonUp += Line_MouseLeftButtonUp;
                        lineUc.isCanDrag = false;
                        canvas.Children.Add(lineUc);
                    }
                    else
                    {
                        //不支持的类型
                    }
                }
                this.printPanel.HorizontalAlignment = System.Windows.HorizontalAlignment.Left;
                this.printPanel.Children.Add(canvas);
            }
            else
            {
                this.printPanel.HorizontalAlignment = System.Windows.HorizontalAlignment.Center;
                TextBlock tb = new TextBlock()
                {
                    Text = "没有自定义磅单",
                    HorizontalAlignment = System.Windows.HorizontalAlignment.Center,
                    VerticalAlignment = VerticalAlignment.Center,
                    Foreground = Brushes.Red,
                    FontSize = 14
                };
                this.printPanel.Children.Add(tb);
            }
        }

        private void BindingValueToCustomerUi(SysCustomizeBillVo vo)
        {
            if (vo != null)
            {
                if (this.printPanel.Children[0] is Canvas canvas)
                {
                    Task.Delay(500).ContinueWith((t) =>
                    {
                        this.Dispatcher.Invoke(() =>
                        {
                            // start  
                            for (int i = 0; i < canvas.Children.Count; i++)
                            {
                                var ui = canvas.Children[i];

                                if (ui is DragUc uc)
                                {
                                    if (uc.Name.StartsWith(Constant.StaticTextNamePre))
                                    {
                                        // static Text ，not do 
                                    }
                                    else
                                    {
                                        //var v = GetBillValue(uc.Name.Replace("Uc", ""));                                        
                                        // uc.SetValueText(v);
                                        // uc.Value = v;
                                    }
                                }
                                else if (ui is DragLineUc lineUc)
                                {
                                    if (lineUc.Name.Equals(Constant.QrCodeName) || lineUc.Name.Equals(Constant.BarCodeName))
                                    {
                                        Border border = lineUc.Content as Border;
                                        Image img = border.Child as Image;
                                        ShowImageSourceAsync(img, lineUc.Name, vo);
                                    }
                                }
                                else
                                {
                                    //不支持的类型
                                }
                            }
                        });
                    });
                }
            }
        }

        private string GetBillValue(string fieldName)
        {
            mWeighingBill ??= WeighingBillDao.Instance.FindById(mBillId);
            if (mWeighingBill == null)
            {
                return "";
            }
            Type t = mWeighingBill.GetType();

            var fieldInfo = t.GetField(fieldName);

            try
            {
                string res;
                if (fieldInfo.FieldType == typeof(DateTime) || fieldInfo.FieldType == typeof(DateTime?))
                {
                    var dt = fieldInfo.GetValue(mWeighingBill) as DateTime?;
                    if (dt != null)
                    {
                        res = DateTimeHelper.Format(dt.Value, "yyyy-MM-dd HH:mm:ss");
                        return res;
                    }
                    else
                    {
                        return "";
                    }
                }
                if (fieldInfo.Name.Equals("printTimes"))
                {

                    Int32? times = fieldInfo.GetValue(mWeighingBill) as Int32?;
                    if (times == null)
                    {
                        return "1";
                    }
                    else
                    {
                        int ii = times.Value + 1;
                        return ii + "";
                    }
                }

                return fieldInfo.GetValue(mWeighingBill)?.ToString() ?? "";
            }
            catch (Exception ex)
            {

            }
            return "";

        }


        private void ShowImageSourceAsync(Image image, string name, SysCustomizeBillVo vo)
        {
            Task.Delay(500).ContinueWith((t) =>
            {
                this.Dispatcher.Invoke(() =>
                {
                    if (name.Equals(Constant.QrCodeName))
                    {
                        if (vo.QrContentVo.QrContentType == QrContentType.Number)
                        {
                            CommonFunction.ShowBillNumberQrCode(image, mWeighingBill?.number??"");
                        }
                        else if (vo.QrContentVo.QrContentType == QrContentType.ImageUrl)
                        {

                            if (App.Config.ImgConfig.OosType == OosType.Local)
                            {
                                CommonFunction.ShowBillNumberQrCode(image, mWeighingBill?.number??"");
                            }
                            else if (App.Config.ImgConfig.OosType == OosType.AliYun)
                            {
                                CommonFunction.ShowAliyunOosQrCode(image, mWeighingBill?.number);
                            }
                            else
                            {
                                //TODO 显示其它类型的二维码
                            }
                        }
                        else
                        {
                            //显示自定义 规则数据 的二维码
                            var qrContent = CommonFunction.GetQrContentByRules(vo.QrContentVo, mWeighingBill);
                            if (!qrContent.IsNullOrEmpty())
                            {
                                CommonFunction.ShowQrCode(image, qrContent);
                            }
                        }
                    }
                    else
                    {
                        var st = mWeighingBill.number.Substring(mWeighingBill.number.LastIndexOf("-") + 1);
                        CommonFunction.ShowBillNumberBarCode(image, st);
                    }
                });
            });
        }


        /// <summary>
        /// cunt down automatic print
        /// </summary>
        private void AutoPrint()
        {
            if (!isAutoPrint) return;
            int autoSeconds = App.Config.BillPrintConfig.AutoPrintInterval;

            if (CuontDownPrintTimer == null)
            {
                CuontDownPrintTimer = new System.Timers.Timer(1000);
                CuontDownPrintTimer.Elapsed += (sender, args) =>
                {
                    autoSeconds--;
                    Thread.Sleep(1000);
                    if (autoSeconds <= 0)
                    {
                        CuontDownPrintTimer?.Stop();
                        this.Dispatcher.Invoke(() =>
                        {
                            this.PrintBtn.Content = "打印";
                            Print();
                            this.PrintBtn.IsEnabled = false;
                        });
                    }
                    else
                    {
                        this.Dispatcher.Invoke(() =>
                        {
                            this.PrintBtn.IsEnabled = false;
                            this.PrintBtn.Content = "打印 " + autoSeconds + "s";
                        });
          
                    }
                };
                CuontDownPrintTimer.Start();
            }
        }

        private void PrintBtn_Click(object sender, RoutedEventArgs e)
        {
            isClickPrint = true;
            UICapture();
            Print();
        }

        public void Print()
        {
            if (isAutoPrint == false && isClickPrint == false)
            {
                return;
            }
            var cb = this.printPanel.Children[0] as TextBlock;
            if (cb != null && cb.Name == "NoCustomerContent")
            {
                Growl.Info("没有要打印的内容", this.Name);
                return;
            }
            this.PrintBtn.IsEnabled = false;
            try
            {
                PrintQueue? printQueue = CommonFunction.GetPrintQueue(mPrintType);
                if (printQueue == null || printQueue.IsOffline == true)
                {
                    throw new Exception("打印机不可用！");
                }
                string description = mPrintType == WeightingBillType.WeighintBill ? "磅单打印" : "非磅单打印";
                var printDialog = new PrintDialog
                {
                    CurrentPageEnabled = true,
                    PageRange = new PageRange(1),
                    PrintQueue = printQueue,
                };

                this.Dispatcher.BeginInvoke(new Action(delegate
                {
                    //打印
                    printDialog.PrintVisual(this.printPanel.Children[0], description);

                    //打印磅单才更新打印时间
                    if (mPrintType == WeightingBillType.WeighintBill)
                    {
                        mWeighingBillVo.PrintTimes++;
                        mWeighingBillVo.PrintDateTime = DateTime.Now;
                        mWeighingBillVo.Type = null;// can't update type
                        WeighingBillDao.Instance.Update(mWeighingBillVo.mWeighingBill);
                    }
                }));

                Growl.Info("打印成功", this.Name);
                //after 3s close this window
                DelayCloseWin(3);
                this.Close();
            }
            catch (Exception e)
            {
                string msg = $"打印出错：{e.Message}";
                ConsoleHelper.writeLine(msg);
                Growl.Error(msg, this.Name);
                Log.Error(msg);
                CommonFunction.SpeakAsync(msg);
            }
            this.PrintBtn.IsEnabled = true;
        }

        private void UICapture()
        {
            //非磅单不截图
            if (mPrintType != WeightingBillType.WeighintBill) return;

            try
            {
                if (BillImageDao.Instance.IsScreemExist(mWeighingBillVo.Id))
                {
                    Log.Info(mWeighingBillVo.Number + "磅单截图已经存在");
                    return;
                }
                string filePath = App.Config.ImgConfig.CapturePath;
                if (!(filePath.Contains("\\") || filePath.Contains("\\\\")))
                {
                    filePath = UrlHelper.Decode(App.Config.ImgConfig.CapturePath);
                }
                if (String.IsNullOrEmpty(filePath))
                {
                    filePath = System.IO.Path.Combine(FileHelper.GetRunTimeRootPath(), "capture/bill/");
                }
                else
                {
                    string d = DateTime.Now.Date.ToString("yyyy-MM-dd");
                    filePath += $"/{d}/bill";
                }

                if (!FileHelper.FolderExistsCreater(filePath))
                {
                    Log.Error("磅单截图目录不存在！");
                }
                String fileName;

                if (string.IsNullOrEmpty(mWeighingBillVo.Number))
                {
                    fileName = Guid.NewGuid() + Constant.CaputureSuffix;
                }
                else
                {
                    fileName = mWeighingBillVo.Number + Constant.BillCaputureSuffix;
                }
                String fileNamePath = System.IO.Path.Combine(filePath, fileName);
                FrameworkElement ui = null;
                if (this.printPanel.Children[0] is UserControl)
                {
                    ui = this.printPanel.Children[0] as UserControl;
                }
                else if (this.printPanel.Children[0] is Canvas)
                {
                    ui = this.printPanel.Children[0] as Canvas;
                }
                if (ui != null)
                {
                    int w = (int)ui.ActualWidth;
                    int h = (int)ui.ActualHeight;
                    SaveToImage(ui, fileNamePath, w, h);
                }
            }
            catch (Exception e)
            {
                Log.Error("磅单截图异常：" + e.Message, e.StackTrace, true);
            }

        }
        private void SaveToImage(UIElement ui, string fileName, int width, int height)
        {
            try
            {
                System.IO.FileStream fs = new System.IO.FileStream(fileName, System.IO.FileMode.Create);
                RenderTargetBitmap bmp = new RenderTargetBitmap(width, height, 96d, 96d, PixelFormats.Pbgra32);
                bmp.Render(ui);

                BitmapEncoder encoder = new PngBitmapEncoder();
                encoder.Frames.Add(BitmapFrame.Create(bmp));
                encoder.Save(fs);
                fs.Close();

                BillImageDao.Instance.SaveCuptureImage(mWeighingBillVo.mWeighingBill.number, fileName, (int)CamaraPosition.Screen, "磅单图片");

                isCaptured = true;
            }
            catch (Exception ex)
            {
                Log.Error("磅单图片截取出错：" + ex.Message, ex.StackTrace, true);
            }
        }

        #region 切换打印内容

        private void DelayCloseWin(int second)
        {
            mTime = new Timer(delegate
            {
                this.Dispatcher.BeginInvoke(new Action(delegate
                {
                    this.Close();
                }), System.Windows.Threading.DispatcherPriority.Send);
            }, null, second * 1000, Timeout.Infinite);
        }

        private void Chenged_Print_Rb(object sender, RoutedEventArgs e)
        {
            if (!IsLoaded) return;
            if (this.WeighingBillRb.IsChecked == true)
            {
                mPrintType = WeightingBillType.WeighintBill;
            }
            else if (this.ExitSlipRb.IsChecked == true)
            {
                mPrintType = WeightingBillType.ExitSlip;
            }
            else if (this.loadingBillRb.IsChecked == true)
            {
                mPrintType = WeightingBillType.LoadingBill;
            }
            else if (this.UnloadingBillRb.IsChecked == true)
            {
                mPrintType = WeightingBillType.UnLoadingBill;
            }
            ChangePrintContent();

        }
        private void ChangePrintContent()
        {
            if (mPrintType == WeightingBillType.WeighintBill)
            {
                SetWeighingBillPrintContent();
            }
            else
            {
                SetNoBillPrintContent();
            }
        }
        #endregion

        /// <summary>
        /// 设置磅单打印内容
        /// </summary>
        private void SetWeighingBillPrintContent()
        {
            this.printPanel.Children.Clear();
            SysCustomizeBillVo customerBillVo;
            if (mWeighingBillVo.Type == (int)WeightingBillType.Buy)
            {
                customerBillVo = GetCustomerBillVo(WeightingBillType.Buy);
                if (customerBillVo != null)
                {
                    SetCustromerUi(customerBillVo);
                    BindingValueToCustomerUi(customerBillVo);
                }
                else
                {
                    this.printPanel.Children.Add(new InPrint() { DataContext = mWeighingBillVo });
                }
            }
            else if (mWeighingBillVo.Type == (int)WeightingBillType.Sale)
            {
                customerBillVo = GetCustomerBillVo(WeightingBillType.Sale);
                if (customerBillVo != null)
                {
                    SetCustromerUi(customerBillVo);
                    BindingValueToCustomerUi(customerBillVo);
                }
                else
                {
                    this.printPanel.Children.Add(new OutPrint() { DataContext = mWeighingBillVo });
                }
            }
            else if (mWeighingBillVo.Type == (int)WeightingBillType.Self)
            {
                customerBillVo = GetCustomerBillVo(WeightingBillType.Self);
                if (customerBillVo != null)
                {
                    SetCustromerUi(customerBillVo);
                    BindingValueToCustomerUi(customerBillVo);
                }
                else
                {
                    this.printPanel.Children.Add(new OrtherPrintUc() { DataContext = mWeighingBillVo });
                }

            }
            else if (mWeighingBillVo.Type == (int)WeightingBillType.Foreign)
            {
                customerBillVo = GetCustomerBillVo(WeightingBillType.Foreign);
                if (customerBillVo != null)
                {
                    SetCustromerUi(customerBillVo);
                    BindingValueToCustomerUi(customerBillVo);
                }
                else
                {
                    this.printPanel.Children.Add(new OrtherPrintUc() { DataContext = mWeighingBillVo });
                }
            }
            else if (mWeighingBillVo.Type == (int)WeightingBillType.Mixture)
            {
                customerBillVo = GetCustomerBillVo(WeightingBillType.Mixture);
                if (customerBillVo != null)
                {
                    SetCustromerUi(customerBillVo);
                    BindingValueToCustomerUi(customerBillVo);
                }
                else
                {
                    this.printPanel.Children.Add(new InPrint() { DataContext = mWeighingBillVo });
                }
            }

            if (VerifyPrintTimes())
            {
                // automatic print
                AutoPrint();
            }
            else
            {
                this.PrintBtn.IsEnabled = false;
                Growl.Error("打印次数己超出");

                DelayCloseWin(3);
            }
        }


        /// <summary>
        /// 设置 非磅单 打印内容
        /// </summary>
        private void SetNoBillPrintContent()
        {
            this.printPanel.Children.Clear();
            SysCustomizeBillVo? customerBillVo = GetCustomerBillVo(mPrintType);
            if (customerBillVo != null)
            {
                SetCustromerUi(customerBillVo);
                BindingValueToCustomerUi(customerBillVo);
            }
            else
            {
                var title = mPrintType == WeightingBillType.ExitSlip ? "出门条" :
                    (mPrintType == WeightingBillType.LoadingBill ? "装货单" :
                    (mPrintType == WeightingBillType.UnLoadingBill ? "卸货单" : ""));
                this.printPanel.Children.Add(new TextBlock()
                {
                    HorizontalAlignment = System.Windows.HorizontalAlignment.Center,
                    VerticalAlignment = VerticalAlignment.Center,
                    FontSize = 14,
                    Margin= new Thickness(10),
                    Name="NoCustomerContent",
                    Text = $"请先自定义 {title} 再打印"
                });
            }

            // automatic print
            AutoPrint();
        }
    }
}
